package leetcode.editor.cn.q1_300.q50;

import java.util.ArrayList;
import java.util.List;

/**
 * @author qidi
 * @date 2021-12-09 10:59:05
 */
class Q0054_SpiralMatrix {

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            int rows = 0;
            int rowe = matrix.length;
            int cols = 0;
            int cole = matrix[0].length;

            List<Integer> res = new ArrayList<>();
            while (true) {
                // 向左
                for (int i = cols; i < cole; i++) {
                    res.add(matrix[rows][i]);
                }
                rows++;
                if (rows == rowe) break;
                // 向下
                for (int i = rows; i < rowe; i++) {
                    res.add(matrix[i][cole - 1]);
                }
                cole--;
                if (cols == cole) break;
                // 向右
                for (int i = cole - 1; i >= cols; i--) {
                    res.add(matrix[rowe - 1][i]);
                }
                rowe--;
                if (rows == rowe) break;
                // 向上
                for (int i = rowe - 1; i >= rows; i--) {
                    res.add(matrix[i][cols]);
                }
                cols++;
                if (cols == cole) break;
            }

            return res;
        }
    }
    //leetcode submit region end(Prohibit modification and deletion)


    public static void main(String[] args) {
        Solution solution = new Q0054_SpiralMatrix().new Solution();
        System.out.println(solution.spiralOrder(new int[][]{
                {1, 2, 3}, {4, 5, 6}, {7, 8, 9}
        }));
        System.out.println(solution.spiralOrder(new int[][]{
                {1, 2}, {4, 5}, {7, 8}
        }));
        System.out.println(solution.spiralOrder(new int[][]{
                {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}
        }));
        System.out.println(solution.spiralOrder(new int[][]{
                {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}
        }));
        System.out.println(solution.spiralOrder(new int[][]{
                {1, 2, 3, 4}, {5, 6, 7, 8}
        }));
    }
}